package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;

import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.SundayCountDto;
import org.itboys.mobile.service.mongo.mobile.SundayMobileCartService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：江雄
 * 日期：2017年5月10日
 * 描述：天街_金融_全球购_购物车_controller_mobile
 */
@Controller
@RequestMapping("/tianjie/mobile/finance/globe/cart")
public class SundayMobileCartController extends BaseController {
    @Autowired
    private SundayMobileCartService cartService;


    /**
     * 获取购物车。购物车ID集合参数说明：可传入此参数，核算购物车总价（如系统含满减，多件折扣等促销）
     * @param request
     * @param response
     * @param cartIds
     */
    @RequestMapping(value="/getCart",method= {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value="【全球购-购物车】获取购物车商品，不分页")
    public void getCart(HttpServletRequest request,
             HttpServletResponse response,
           // @ApiParam(required = false, name = "villageId", value = "小区ID。用户版传入") @RequestParam(value="villageId",required=false) Long villageId,
            @ApiParam(required = false, name = "cartIds", value = "购物车ID集合(非商品ID)。如：cardIds=1,2,3。可传入此参数，核算购物车总价（如系统含满减，多件折扣等促销）") @RequestParam(value = "cartIds", required = false) List<Long> cartIds,
            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            SundayCountDto result = cartService.getCart(memberId, cartIds, SundayCommonConstants.cart_type_cart);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/tianjie/mobile/finance/globe/cart/getCart----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 【用户版和管理版】加入购物车（支持批量新增）。商品ID集合和数量集合，需要对应。
     * @param request
     * @param response
     */
    @RequestMapping(value="/addCart",method= {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value="【全球购-购物车】加入购物车")
    public void addCart(HttpServletRequest request,
                        HttpServletResponse response,
                       // @ApiParam(required = true, name = "memberId", value = "用户ID") @RequestParam(value="memberId",required=true) Long memberId,
                       // @ApiParam(required = false, name = "villageId", value = "小区ID。用户版传入") @RequestParam(value="villageId",required=false) Long villageId,
                        @ApiParam(required = true, name = "productId", value = "商品ID") @RequestParam(value = "productId", required = true) Long productId,
                        @ApiParam(required = true, name = "num", value = "数量") @RequestParam(value = "num", required = true)Integer num,
                        @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();


            param.put("productId",productId);//实际是字符串。cartIds=1,2,3
            param.put("num",num);//实际是字符串。

            param.put("nonce", nonce);
            param.put("sign", sign);
           /* boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/



            Long memberId = AccountIdHoldUtils.getMemberId();
            cartService.addCart(memberId, productId , num, SundayCommonConstants.cart_type_cart);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/tianjie/mobile/finance/globe/cart/addCart----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 【用户版和管理版】修改购物车数量（支持批量修改）。商品ID集合和数量集合，需要对应
     * @param request
     * @param response

     */
    @RequestMapping(value="/updateCart",method= {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value="【全球购-购物车】修改购物车数量")
    public void updateCart(HttpServletRequest request,
                        HttpServletResponse response,
                           @ApiParam(required = true, name = "cartId", value = "购物车ID(非商品ID)") @RequestParam(value = "cartId", required = true) Long cartId,
                           @ApiParam(required = true, name = "num", value = "数量（修改后的数量）") @RequestParam(value = "num", required = true)Integer num,
                           @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {

        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            //param.put("villageId",villageId);

            param.put("cartId",cartId);//实际是字符串。cartIds=1,2,3
            param.put("num",num);//实际是字符串。
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            cartService.updateCart( memberId, cartId ,num);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/tianjie/mobile/finance/globe/cart/updateCart----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    /**
     * 【用户版和管理版】修改购物车数量（支持批量修改）。商品ID集合和数量集合，需要对应
     * @param request
     * @param response
     * @param cartIds
     * @param nonce
     * @param sign
     */
    @RequestMapping(value="/deleteCart",method= {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value="【全球购-购物车】删除购物车（支持批量删除）")
    public void deleteCart(HttpServletRequest request,
                           HttpServletResponse response,
                            @ApiParam(required = true, name = "cartIds", value = "购物车ID集合(非商品ID)。如：cardIds=1,2,3") @RequestParam(value = "cartIds", required = true) List<Long> cartIds,
                           @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                           @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {

        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            StringBuilder cartIdsStr=new StringBuilder();
            for(Long cartId:cartIds){
                cartIdsStr.append(cartId+",");
            }
            param.put("cartIds",cartIdsStr.substring(0,cartIdsStr.length()-1).toString());//实际是字符串。cartIds=1,2,3
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            cartService.deleteCart(cartIds , memberId, SundayCommonConstants.cart_type_cart);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/cart/deleteCart----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
}
